﻿using System;
using System.Globalization;
using Monkey.Warrenty.Biz;
using Monkey.Warrenty.EntityModel;

namespace MonkeyWarranty.Web.InstantTickets
{
    public partial class NewEmployee : System.Web.UI.Page
    {
        private static InstantTicketBiz _instantTicketBiz;
        private static InstantTicketBiz InstantTicketManager
        {
            get { return _instantTicketBiz ?? (_instantTicketBiz = new InstantTicketBiz()); }
        }

        private long _ticketId;
        private long TicketId
        {
            get
            {
                if (_ticketId <= 0) long.TryParse(Request.Params["ticketId"], out _ticketId);
                return _ticketId;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (TicketId <= 0)
                {
                    lblErrorMessage.Text = Resources.GlobalStrings.InstantTicketNotExisted;
                    btnSave.Enabled = false;
                    return;
                }

                txtStartDate.Text = string.Format("{0:dd/MM/yyyy HH:mm}", DateTime.Now);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            lblErrorMessage.Text = string.Empty;

            // validate inputs
            var employeeId = hidEmployeeId.Value;
            if (string.IsNullOrEmpty(employeeId))
            {
                lblErrorMessage.Text = Resources.GlobalStrings.EmployeeIsRequired;
                return;
            }

            DateTime startDate;
            if (!DateTime.TryParseExact(txtStartDate.Text.Trim(), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out startDate))
            {
                lblErrorMessage.Text = Resources.GlobalStrings.InvalidDate;
                return;
            }

            var descrition = txtDescription.Text;
            var note = txtNote.Text;

            var ticketEmployee = new InstantTicket_Employee
            {
                InstantTicketId = TicketId,
                EmployeeId = int.Parse(employeeId),
                Description = descrition,
                Note = note,
                StartDate = startDate
            };

            // Call Biz Save Product
            InstantTicketManager.CreateTicketEmployee(ticketEmployee);

            Response.Redirect(string.Format("Edit.aspx?id={0}#tabs-3", TicketId));
        }
    }
}